import Vue from 'vue'
import _ from 'underscore'
const  Utils= {


  guid: function (pre="") {
    const timestamp = +new Date() + ''
    const randomNum = parseInt((1 + Math.random()) * 65536) + ''
    return pre+(randomNum + timestamp).toString(32)
  },

  trim: function (value) {
    if (value) {
      value.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
      return value;
    } else {
      return '';
    }
  },
  /**
   * 判断字符串是否以指定字符串结尾
   * @param s
   * @param str
   * @returns {boolean}
   */
  startWith: function (s, str) {
    if (s === null || s === "" || str.length === 0 || s.length > str.length)
      return false;
    if(str.substr(0, s.length) === s)
      return true;
    else
      return false;
  },
  /**
   * 判断字符串是否以指定字符串结尾
   * @param s
   * @param str
   * @returns {boolean}
   */
  endWith: function (s, str) {
    if (s === null || s === "" || str.length === 0 || s.length > str.length)
      return false;
    if(str.substring(str.length - s.length) === s)
      return true;
    else
      return false;
  },
  /**
   * 获取字符串的字节数
   * @param {Sting} val input value
   * @returns {number} output value
   */
  getByteLen: function (val) {
    let len = 0
    for (let i = 0; i < val.length; i++) {
      if (val[i].match(/[^\x00-\xff]/ig) != null) {
        len += 1
      } else {
        len += 0.5
      }
    }
    return Math.floor(len)
  },
  isJSON: function (str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    } else {
      return false;
    }
  },


  getUrlParam: function (key) {
    if (!key) return "";
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      let str = url.substr(1);
      let strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
      }
    }
    return theRequest[key];
  },
  fillBase64Img: function (value) {
    if (value) {
      if (value.indexOf(",") > -1) {
        return value
      } else {
        return "data:image/jpeg;base64," + value
      }
    }
    else {
      return false
    }
  },
  debounce: function (func, wait, immediate) {
    let timeout, args, context, timestamp, result
    const later = function () {
      // 据上一次触发时间间隔
      const last = +new Date() - timestamp

      // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
      if (last < wait && last > 0) {
        timeout = setTimeout(later, wait - last)
      } else {
        timeout = null
        // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
        if (!immediate) {
          result = func.apply(context, args)
          if (!timeout) context = args = null
        }
      }
    }
  }

}


export default Utils


